var tableElem = "LAY-home-ad-list";
var tableToolsElem = "LAY-home-ad-tools";
var formElem = "LAY-home-ad-listform";
var formSubmitElem = "LAY-home-ad-listform-submit";
var formUrl = '/home/adPosition/ad/listform'
var historyUrl = '/home/adPosition/ad/list'
var baseUrl = window.globalConfig.url_ad_list;

layui.use(['common'], function (common) {
    var $ = layui.$
        , admin = layui.admin
        , view = layui.view
        , table = layui.table
        , form = layui.form
        , router = layui.router()

    var position_id = router.search.position_id
    //页面管理
    var tableItem = table.render({
        elem: `#${tableElem}`
        , url: window.globalConfig.url_adPosition_list + "/" + position_id
        , parseData: function (res) {
            sessionStorage.setItem("size_suggest", res.data.position_style)
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.data.adList.length, //解析数据长度
                "data": res.data.adList
            }
        }
        , cols: [[
            {type: 'checkbox', fixed: 'left'}
            , {field: 'ad_id', width: 100, title: 'id', sort: true}
            , {field: 'position_id', width: 100, title: '位置id', sort: true}
            , {
                field: 'media_type', title: '媒体类型', templet: function (d) {
                    if (d.media_type === 1) {
                        return '图片';
                    } else if (d.media_type === 2) {
                        return '视频';
                    }
                }
            }
            , {field: 'ad_name', title: '名称', minWidth: 250, edit: 'text'}
            , {field: 'ad_link', title: '链接地址', minWidth: 100, edit: 'text'}
            , {
                field: 'enabled', title: '是否开启', templet: '#ID-table-ad-enabled-switch'
            }
            , {field: 'orderid', title: '排序', edit: 'text'}
            , {title: '操作', minWidth: 220, align: 'center', fixed: 'right', toolbar: `#${tableToolsElem}`}
        ]]
        , page: true
        , limit: 10
        , limits: [10, 15, 20, 25, 30]
        , text: {none: '暂无数据！'}
    });

    var active = {
        //添加
        add: function (othis) {
            location.hash = `${formUrl}/position_id=${position_id}`;
        }
    };

    $('.layui-btn.layuiadmin-btn-list').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

    // 增删改查
    table.on(`tool(${tableElem})`, function (obj) {
        var data = obj.data;
        if (obj.event === "detail") {  // 查看详情
            location.hash = `${formUrl}/position_id=${position_id}/id=${data.ad_id}/mode=read`;
        } else if (obj.event === 'del') { // 删除详情
            layer.confirm('确定删除此详情？', function (index) {
                layer.close(index);
                admin.req({
                    url: window.globalConfig.url_ad_list + "/" + data.ad_id,
                    type: "DELETE",
                    success: function (res) {
                        common.ctmMsg(res.code, res.msg)
                        tableItem.reloadData()
                    }
                })
            });
        } else if (obj.event === 'edit') {// 修改详情
            location.hash = `${formUrl}/position_id=${position_id}/id=${data.ad_id}`;
        } else if (obj.event === 'copy') {
            layer.confirm('确定复制此广告？', function (index) {
                var field = data
                field.ad_name = field.ad_name + "_" + common.generateRandomRewriteUrl(4)
                delete field.ad_id
                delete field.start_time
                delete field.end_time
                admin.req({
                    url: baseUrl,
                    type: "POST",
                    data: field,
                    success: function (res) {
                        common.ctmMsg(res.code, res.msg)
                        if (res.code === 0) {
                            tableItem.reloadData()
                        }
                    }
                })
            });

        }
    });

});


//表单页
layui.use(['common'], (common) => {
    var admin = layui.admin
        , laydate = layui.laydate
        , $ = layui.$

    // 表单模块
    layui.data.done = function (d) {
        var remoteData = d.data
        layui.use(['form'], function () {
            var form = layui.form;
            form.render(null, formElem); //渲染该模板下的动态表单

            $(".size-suggest").text(sessionStorage.getItem("size_suggest"));
            sessionStorage.removeItem("size_suggest");


            //开始日期
            var insStart = laydate.render({
                elem: '#test-laydate-start'
                , min: 0
                , done: function (value, date) {
                    //更新结束日期的最小日期
                    insEnd.config.min = lay.extend({}, date, {
                        month: date.month - 1
                    });

                    //自动弹出结束日期的选择器
                    insEnd.config.elem[0].focus();
                }
            });

            //结束日期
            var insEnd = laydate.render({
                elem: '#test-laydate-end'
                , min: 0
                , done: function (value, date) {
                    //更新开始日期的最大日期
                    insStart.config.max = lay.extend({}, date, {
                        month: date.month - 1
                    });
                }
            });

            // 加载编辑器
            let editors = {
                'editor': 'des',
            }
            common.loadEditors(remoteData, editors)

            $('#ad_code').on('blur', function () {
                $('#ID-upload-ad_code-img').attr('src', `${window.globalConfig.img_bind_url}` + $(this).val())
            })
            $('#mad_code').on('blur', function () {
                $('#ID-upload-mad_code-img').attr('src', `${window.globalConfig.img_bind_url}` + $(this).val())
            })


            //手机端图片
            common.uploader("ID-upload-ad_code-btn", "ID-upload-ad_code-img", "ad_code")
            //pc端图片
            common.uploader("ID-upload-mad_code-btn", "ID-upload-mad_code-img", "mad_code")

            form.on(`submit(${formSubmitElem})`, function (data) {
                var field = data.field; //获取提交的字段
                field.enabled = field.enabled === undefined ? 0 : field.enabled;
                field = common.getEditorsContent(field, editors)

                let url = window.globalConfig.url_ad_list;
                let type = "POST";
                if (field.ad_id) {
                    url += "/" + field.ad_id;
                    type = "PUT"
                }

                //提交 Ajax 成功后，关闭当前弹层并重载表格
                admin.req({
                    url: url,
                    type: type,
                    data: field,
                    success: function (res) {
                        common.ctmMsg(res.code, res.msg)
                        location.hash = `${historyUrl}/position_id=${layui.router().search.position_id}`
                    }
                })
            });
        });
    };


    // 表格文本修改
    common.tableTextEditor(tableElem, window.globalConfig.url_ad_list, 'ad_id')

    // 表格的切换器修改
    common.tableSwitchEditor('ad-enabled-status', window.globalConfig.url_ad_list)
})